package com.lcf.framework.aspect;

import com.lcf.framework.utils.EntityFileRelativeUtils;
import com.lcf.framework.utils.EntityTranslateUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

/**
 * 实体类翻译
 *
 * @author lcf
 */
@Slf4j
@Aspect
@Component
public class DictAspect {
    @Resource
    private EntityTranslateUtils entityTranslateUtils;
    @Resource
    private EntityFileRelativeUtils entityFileRelativeUtils;

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void controllerPointcut() {
    }

    @Around("controllerPointcut()")
    public Object handleDictAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> targetClass = signature.getDeclaringType();
        if (targetClass.isAnnotationPresent(RequestMapping.class)) {
            // 请求前的操作
            Object[] args = joinPoint.getArgs();

            for (Object arg : args) {
                if (arg != null) {
                    entityFileRelativeUtils.translate(arg);
                }
            }
        }
        //处理请求
        Object result = joinPoint.proceed();

        if (!targetClass.isAnnotationPresent(RequestMapping.class)) {
            return result;
        }

        //请求后的操作
        if (result != null) {
            if (result instanceof Collection<?> collection) {
                if (collection.isEmpty()) {
                    return result;
                }

                Object o = collection.stream().findFirst().orElse(null);
                if (!entityTranslateUtils.isNotJdkClass(o.getClass())) {
                    return result;
                }

                return entityTranslateUtils.translate(result);
            }

            Class<?> clazz = result.getClass();
            if (!entityTranslateUtils.isNotJdkClass(clazz)) {
                return result;
            }

            return entityTranslateUtils.translate(result);
        }

        return null;
    }
}
